package com.offcn.oauth.token;

import com.alibaba.fastjson.JSON;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.RsaSigner;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;

import java.security.KeyPair;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.HashMap;
import java.util.Map;

public class AdminToken {

    /**
     * 创建令牌，用于登录时远程调用User模块中的方法
     * @return
     */
    public static String createAdminToken(){
        // 证书的路径
        String key_location = "dongyimai.jks";
        // 秘钥库的密码
        String key_password = "dongyimai";
        // 解析文件的密码
        String keypwd = "dongyimai";
        // 别名
        String alias = "dongyimai";

        // 加载证书
        ClassPathResource resource = new ClassPathResource(key_location);

        // 创建秘钥工厂
        KeyStoreKeyFactory keyFactory = new KeyStoreKeyFactory(resource, key_password.toCharArray());

        // 读取秘钥对 （公钥 和 私钥）
        KeyPair keyPair = keyFactory.getKeyPair(alias, keypwd.toCharArray());

        // 获取公钥
        RSAPublicKey publicKey = (RSAPublicKey)keyPair.getPublic();

        // 获取私钥
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

        // 定义存储的内容 载荷
        Map<String, Object> map = new HashMap<>();
        map.put("name","admin");
        map.put("role","ADMIN");

        String str = JSON.toJSONString(map);

        // 签名需要通过私钥
        Jwt token = JwtHelper.encode(str, new RsaSigner(privateKey));

        return token.getEncoded();
    }
}
